<template>
  <div class="container mx-auto px-4 py-8">
    <div class="max-w-6xl mx-auto space-y-8">
      <!-- 操作说明组件 -->
      <InstructionsCard 
        :instructions="instructions" 
        :image-base-url="'/src/assets'" 
      />

      <!-- 参数配置卡片 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center mb-6">
          <div class="p-2 bg-blue-50 rounded-lg">
            <Settings class="h-6 w-6 text-blue-500" />
          </div>
          <h2 class="text-xl font-semibold text-gray-800 ml-3">参数配置</h2>
        </div>
        
        <ConfigurableForm
          :config="formConfig"
          v-model="localFormData"
          @update:modelValue="updateFormData"
        />

        <div class="flex gap-3 mt-6">
          <button 
            @click="formatSQL"
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors duration-200"
          >
            <Code class="h-5 w-5 mr-2" />
            格式化SQL
          </button>
          <button 
            @click="extractFields"
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-green-600 bg-green-50 rounded-lg hover:bg-green-100 transition-colors duration-200"
          >
            <FileText class="h-5 w-5 mr-2" />
            提取字段
          </button>
          <button 
            @click="clearSQL"
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors duration-200"
          >
            <Trash class="h-5 w-5 mr-2" />
            清空SQL
          </button>
          <button 
            @click="generateCode"
            class="inline-flex items-center px-6 py-2 text-sm font-medium text-purple-600 bg-purple-50 rounded-lg hover:bg-purple-100 transition-colors duration-200"
          >
            <Code class="h-5 w-5 mr-2" />
            生成代码
          </button>
        </div>
      </div>

      <!-- SQL 预览卡片 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center mb-6">
          <div class="p-2 bg-blue-50 rounded-lg">
            <Code class="h-6 w-6 text-blue-500" />
          </div>
          <h2 class="text-xl font-semibold text-gray-800 ml-3">SQL 预览</h2>
        </div>
        <div class="bg-gray-50 rounded-lg p-4">
          <v-md-preview :text="sqlPreviewContent" />
        </div>
      </div>

      <!-- 字段信息卡片 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center mb-6">
          <div class="p-2 bg-blue-50 rounded-lg">
            <Table class="h-6 w-6 text-blue-500" />
          </div>
          <h2 class="text-xl font-semibold text-gray-800 ml-3">字段信息</h2>
        </div>
        <TableDetails
          :data="tableData"
          :columns="tableColumns"
          @update:data="updateTableData"
        />
      </div>

      <!-- 生成的代码预览 -->
      <GeneratedCode 
        v-if="isVisible && generatedCode" 
        :code-content="generatedCode" 
        :is-visible="isVisible"
        @copy-success="handleCopySuccess"
        @copy-error="handleCopyError"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { Settings, Code, Table, FileText, Trash } from 'lucide-vue-next';
import { ElMessage } from 'element-plus';
import GeneratedCode from '@/components/common/GeneratedCode.vue';
import ConfigurableForm from '@/components/common/ConfigurableForm.vue';
import TableDetails from '@/components/common/TableDetails.vue';
import InstructionsCard from '@/components/common/InstructionsCard.vue';
import { format } from 'sql-formatter';
import { queryApiColumns } from '@/config/tableColumns';
import { queryApiConfig } from '@/config/formConfigs';
import { useQueryApiCodeGeneration } from '@/composables/useQueryApiCodeGeneration';
import instructions from '@/assets/query-api-instructions.md';

const formConfig = queryApiConfig;
const localFormData = reactive({
  programId: '',
  interfaceFunction: '',
  sql: ''
});

const tableData = ref([]);
const isVisible = ref(false);
const generatedCode = ref('');
const tableColumns = queryApiColumns;

const { generateQueryApiCode } = useQueryApiCodeGeneration();

const updateFormData = (newValue) => {
  Object.assign(localFormData, newValue);
};

const formatSQL = () => {
  try {
    const formattedSQL = format(localFormData.sql);
    localFormData.sql = formattedSQL;
    ElMessage.success('SQL已格式化');
  } catch (error) {
    ElMessage.error('SQL格式化失败');
  }
};

const extractFields = () => {
  const selectRegex = /SELECT\s+(.+?)\s+FROM/i;
  const match = localFormData.sql.match(selectRegex);

  if (match) {
    const fields = match[1].split(',').map(field => {
      const [name, type] = field.trim().split(/\s+/);
      return {
        field: name,
        type: type || '',
        length: '',
        defaultValue: '',
        required: false,
        description: '',
        referenceTableField: ''
      };
    });
    tableData.value = fields;
    ElMessage.success('字段已提取');
  } else {
    ElMessage.error('无法提取字段');
  }
};

const clearSQL = () => {
  localFormData.sql = '';
  ElMessage.info('SQL已清空');
};

const updateTableData = (newData) => {
  tableData.value = newData;
};

const generateCode = () => {
  generatedCode.value = generateQueryApiCode(localFormData, tableData.value);
  if (generatedCode.value) {
    isVisible.value = true;
  } else {
    ElMessage.warning('无法生成代码，请检查输入');
  }
};

const handleCopySuccess = () => {
  ElMessage.success('代码已成功复制到剪贴板');
};

const handleCopyError = () => {
  ElMessage.error('复制失败，请手动复制代码');
};

const sqlPreviewContent = computed(() => {
  return `\`\`\`sql\n${localFormData.sql}\n\`\`\``;
});
</script>